package cn.ix.spring.security.service.impl;

import cn.ix.spring.security.config.JwtConfig;
import cn.ix.spring.security.dto.AccountDTO;
import cn.ix.spring.security.entity.Account;
import cn.ix.spring.security.service.AccountService;
import cn.ix.spring.security.util.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author lzw
 * @description AccountServiceImpl
 * @date 2022/3/1
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private JwtConfig jwtConfig;

    private static Map<String,Account> userMap=new HashMap<>();

    static {
        userMap.put("admin",new Account("admin","123456"));
        userMap.put("test",new Account("test","123456"));
    }
    /**
     * 登录
     *
     * @param account
     * @return
     */
    @Override
    public AccountDTO login(Account account) {
        String username=account.getUsername();
        Account account1=userMap.get(username);
        if(Objects.isNull(account1)){
            throw new RuntimeException("user not fount");
        }
        if(!Objects.equals(account.getPassword(),account1.getPassword())){
            throw new RuntimeException("用户名密码错误");
        }
        AccountDTO accountDTO= new AccountDTO();
        BeanUtils.copyProperties(account,accountDTO);
        setToken(accountDTO);
        return accountDTO;
    }

    /**
     * 刷新Token
     *
     * @param account
     * @return
     */
    @Override
    public AccountDTO refreshToken(AccountDTO account) {
        // todo
        return null;
    }


    /**
     * 设置token
     * @param accountDTO
     * @return
     */
    private void setToken(AccountDTO accountDTO){
        String authenticateToken = JwtUtils.generatorJwtToken(accountDTO.getUsername(),
                jwtConfig.getUserId(),
                jwtConfig.getTokenExpireSecond(),
                jwtConfig.getSecretKey());

        String refreshToken = JwtUtils.generatorJwtToken(accountDTO.getUsername(),
                jwtConfig.getUserId(),
                jwtConfig.getRefreshTokenExpiredSecond(),
                jwtConfig.getSecretKey());

        accountDTO.setToken(authenticateToken);
        accountDTO.setRefreshToken(refreshToken);
    }
}
